/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.ibatis.extension.plugins.inner;

import com.je.ibatis.extension.conditions.ConditionsWrapper;
import com.je.ibatis.extension.exception.JeIbatisRuntimeException;
import com.je.ibatis.extension.plugins.pagination.DialectFactory;
import com.je.ibatis.extension.plugins.pagination.Pagination;
import com.je.ibatis.extension.plugins.pagination.dialects.IDialect;
import org.apache.ibatis.executor.parameter.ParameterHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.StatementType;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.scripting.defaults.DefaultParameterHandler;
import org.springframework.util.StringUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Map;
import java.util.Properties;

/**
 * 内部分页插件
 */
public class PagableInnerInterceptor extends AbstractInnerInterceptor {

    protected final String MARK = "pagable";
    /**
     * 方言类型
     */
    private String dialectType;
    /**
     * 方言实现类
     */
    private String dialectClazz;

    public PagableInnerInterceptor() {
        this.enable = true;
    }

    @Override
    public String getMark() {
        return MARK;
    }

    public String getDialectType() {
        return dialectType;
    }

    public void setDialectType(String dialectType) {
        this.dialectType = dialectType;
    }

    public String getDialectClazz() {
        return dialectClazz;
    }

    public void setDialectClazz(String dialectClazz) {
        this.dialectClazz = dialectClazz;
    }

    @Override
    public void beforePrepare(StatementHandler sh, Connection connection, Integer transactionTimeout) throws SQLException {
        MetaObject metaStatementHandler = SystemMetaObject.forObject(sh);

        //获取方言
        IDialect dialect = null;
        if (dialectType != null && !"".equals(dialectType)) {
            dialect = DialectFactory.getDialect(dialectType);
        } else if (dialectClazz != null && !"".equals(dialectClazz)) {
            try {
                Class<?> clazz = Class.forName(dialectClazz);
                if (IDialect.class.isAssignableFrom(clazz)) {
                    dialect = (IDialect) clazz.newInstance();
                }
            } catch (ClassNotFoundException e) {
                throw new JeIbatisRuntimeException("Class :" + dialectClazz + " is not found");
            } catch (InstantiationException e) {
                throw new JeIbatisRuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new JeIbatisRuntimeException(e);
            }
        } else {
            dialect = DialectFactory.getDialectByUrl(connection.getMetaData().getURL());
        }

        //未配置方言则抛出异常
        if (dialect == null) {
            throw new JeIbatisRuntimeException("The value of the dialect property in mybatis configuration.xml is not defined.");
        }

        // 先判断是不是SELECT操作
        MappedStatement mappedStatement = (MappedStatement) metaStatementHandler.getValue("delegate.mappedStatement");
        if (SqlCommandType.SELECT != mappedStatement.getSqlCommandType()
                || StatementType.CALLABLE == mappedStatement.getStatementType()) {
            return;
        }

        // 针对定义了rowBounds，做为mapper接口方法的参数
        BoundSql boundSql = (BoundSql) metaStatementHandler.getValue("delegate.boundSql");
        Object paramObj = boundSql.getParameterObject();

        // 判断参数里是否有page对象
        Pagination page = null;
        ConditionsWrapper wrapper = null;
        if (paramObj instanceof Pagination) {
            page = (Pagination) paramObj;
        } else if (paramObj instanceof Map) {
            for (Object arg : ((Map<?, ?>) paramObj).values()) {
                if (arg instanceof Pagination) {
                    page = (Pagination) arg;
                    break;
                } else if (arg instanceof ConditionsWrapper) {
                    wrapper = (ConditionsWrapper) arg;
                }
            }
        }

        /*
         * 不需要分页的场合，如果 size 小于 0 返回结果集
         */
        if (null == page || page.getSize() < 0) {
            return;
        }

        //分页
        String originalSql = boundSql.getSql();
        if (wrapper != null && originalSql.toUpperCase().indexOf(SqlCommandType.SELECT.name()) == -1) {
            if (StringUtils.isEmpty(wrapper.getSelectColumns())) {
                originalSql = "SELECT * FROM " + wrapper.getTable() + " " + originalSql;
            } else {
                originalSql = "SELECT " + wrapper.getSelectColumns() + " FROM " + wrapper.getTable() + " " + originalSql;
            }
        }

        if (page.isSearchCount()) {
            page = this.count(originalSql, connection, mappedStatement, boundSql, page);
        }
        originalSql = dialect.buildPaginationSql(originalSql, page.getOffsetCurrent(), page.getSize());
        //查询 SQL 设置
        metaStatementHandler.setValue("delegate.boundSql.sql", originalSql);
    }

    /**
     * 查询总记录条数
     *
     * @param sql
     * @param connection
     * @param mappedStatement
     * @param boundSql
     * @param page
     */
    public Pagination count(String sql, Connection connection, MappedStatement mappedStatement, BoundSql boundSql, Pagination page) {
        String sqlUse = sql;
        int order_by = sql.toUpperCase().lastIndexOf("ORDER BY");
        if (order_by > -1) {
            sqlUse = sql.substring(0, order_by);
        }
        StringBuffer countSql = new StringBuffer("SELECT COUNT(1) AS TOTAL FROM (");
        countSql.append(sqlUse).append(") A");
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            pstmt = connection.prepareStatement(countSql.toString());
            BoundSql countBS = new BoundSql(mappedStatement.getConfiguration(), countSql.toString(),
                    boundSql.getParameterMappings(), boundSql.getParameterObject());
            ParameterHandler parameterHandler = new DefaultParameterHandler(mappedStatement,
                    boundSql.getParameterObject(), countBS);
            parameterHandler.setParameters(pstmt);
            rs = pstmt.executeQuery();
            int total = 0;
            if (rs.next()) {
                total = rs.getInt(1);
            }
            page.setTotal(total);
            /**
             * 当前页大于总页数，当前页设置为第一页
             */
//            if (page.getCurrent() > page.getPages()) {
//                page = new Pagination(1, page.getSize());
//                page.setTotal(total);
//            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                }
                if (pstmt != null) {
                    pstmt.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return page;
    }

    @Override
    public void setProperties(Properties properties) {
        String enableField = getMark() + DOT + ENABLE_FIELD;
        if (properties.containsKey(enableField)) {
            setEnable("1".equals(properties.getProperty(enableField)) || "true".equals(properties.getProperty(enableField)));
        } else {
            setEnable(true);
        }

        String dialectType = properties.getProperty(getMark() + DOT + "dialectType");
        String dialectClazz = properties.getProperty(getMark() + DOT + "dialectClazz");
        if (dialectType != null && !"".equals(dialectType)) {
            this.dialectType = dialectType;
        }
        if (dialectClazz != null && !"".equals(dialectClazz)) {
            this.dialectClazz = dialectClazz;
        }
    }

}
